﻿using System;
using System.Configuration;
using System.IO;
using System.Xml.Linq;

namespace SPContrib.Extensions
{
    /// <summary>
    /// Extensions for the FileInfo class
    /// </summary>
    public static class FileInfoExtensions
    {
        /// <summary>
        /// Returns an instance of Configuration that represents the file
        /// </summary>
        public static Configuration AsConfiguration(this FileInfo instance)
        {
            Configuration configuration = null;

            try
            {
                var map = new ExeConfigurationFileMap { ExeConfigFilename = instance.FullName };
                configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

                if (configuration.HasFile == false)
                {
                    throw "FileInfoExtensions: The Configuration instance has no file associated. ExeConfigurationFileMap was constructed with an invalid filepath."
                            .AsException();
                }
            }
            catch (Exception e)
            {
                "FileInfoExtensions: Failed to translate file '{0}' to a Configuration instance."
                    .AsException(e, instance.FullName);
            }

            return configuration;
        }

        /// <summary>
        /// Returns an instance of XDocument that represents the file
        /// </summary>
        public static XDocument AsXml(this FileInfo instance)
        {
            return XDocument.Load(instance.FullName);
        }
    }
}
